import sqlite3
import os.path


class DbManager():    
    
    def connect(self, dbname):
        if os.path.isfile(dbname):
            self.__conn = sqlite3.connect(dbname)            
        #else:
        #    print 'Creating new database...'
        #    self.__conn = self.__create_new(dbname)
        #return 1        
    
    def __create_new(self, dbname):
        conn = sqlite3.connect(dbname)
        conn.execute("CREATE TABLE members (username TEXT, password TEXT, PRIMARY KEY(username));")
        return conn
    
    def add_member(self, username, password):
        try:
            self.__conn.execute("INSERT INTO members (username, password) VALUES(?, ?);", (username, password))
            self.__conn.commit()
            return 1
        except sqlite3.IntegrityError:
            print "Username already exsists! Try a different one..."
            return 0
        
    def get_members(self):
        try:
            cur = self.__conn.cursor()
            cur.execute("SELECT username FROM members;")
        #conn.execute("CREATE TABLE members (username TEXT, password TEXT, PRIMARY KEY(username));")
            return cur.fetchall()
        except sqlite3.Error as e:
            print "An error occurred: " + e.args[0]
            return None
        
    def del_member(self, username):
        try:
            self.__conn.execute("DELETE FROM members WHERE username = ?", [username])
            self.__conn.commit()
            return 1
        except sqlite3.Error as e:
            print "An error occurred: " + e.args[0]
            return 0
    
    def flush_members(self):
        try:
            self.__conn.execute("DELETE FROM members")
            self.__conn.commit()
            return 1
        except sqlite3.Error as e:
            print "An error occurred: " + e.args[0]
            return 0        
        
    def get_password(self, username):
        try:
            c = self.__conn.cursor()
            c.execute("SELECT password FROM MEMBERS WHERE username = ?", [username])
        except sqlite3.Error as e:                       
            print "An error occurred: " + e.args[0]
            return None
        r = c.fetchone()        
        if r:
            return r[0]
        return None
        
            
    def close(self):
        self.__conn.close()
    